package org.lemon.cla.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lemon.cla.pojo.Feedback;
import org.lemon.cla.pojo.User; // 导入 User 实体
import org.lemon.cla.mapper.FeedbackMapper;
import org.lemon.cla.service.IFeedbackService;
import org.lemon.cla.service.IUserService; // 导入 IUserService
import org.lemon.cla.dto.request.FeedbackSearchRequest;
import org.lemon.cla.enums.FeedbackStatusEnum;
import org.lemon.cla.vo.FeedbackVo; // 导入 FeedbackVo
import org.lemon.cla.exception.BusinessException; // 导入 BusinessException
import org.lemon.cla.enums.HttpStatusEnum; // 导入 HttpStatusEnum
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements IFeedbackService {

    @Autowired
    private IUserService userService; // 注入 IUserService 用于检查用户逻辑删除状态

    // 辅助方法：处理 FeedbackVo 中的用户信息
    private FeedbackVo processUserInfo(FeedbackVo feedbackVo) {
        if (feedbackVo == null) return null;
        // 如果用户ID为null（ON DELETE SET NULL 发生），或者用户被逻辑删除
        if (feedbackVo.getUserId() == null || (feedbackVo.getUserIsDeleted() != null && feedbackVo.getUserIsDeleted())) {
            feedbackVo.setUsername("未知用户");
            feedbackVo.setAvatarUrl(null);
            feedbackVo.setRealName("未知");
            feedbackVo.setPhone(null);
            feedbackVo.setEmail(null);
            feedbackVo.setUserRole(null);
        }
        return feedbackVo;
    }

    // 辅助方法：处理分页结果中的用户信息
    private IPage<FeedbackVo> processUserInfoForPage(IPage<FeedbackVo> page) {
        if (page != null && page.getRecords() != null) {
            page.getRecords().forEach(this::processUserInfo);
        }
        return page;
    }

    @Override
    public FeedbackVo getFeedbackVoById(Long feedbackId) {
        FeedbackVo feedbackVo = baseMapper.selectFeedbackVoById(feedbackId);
        return processUserInfo(feedbackVo); // 处理单个 FeedbackVo
    }

    @Override
    public IPage<FeedbackVo> getAllFeedbacksVo(Page<FeedbackVo> page) {
        IPage<FeedbackVo> feedbackPage = baseMapper.selectFeedbackVoPage(page);
        return processUserInfoForPage(feedbackPage); // 处理分页结果
    }

    @Override
    public IPage<FeedbackVo> searchFeedbacksByConditions(Page<FeedbackVo> page, FeedbackSearchRequest request) {
        IPage<FeedbackVo> resultPage = baseMapper.selectFeedbacksVoByMultiConditions(page, request);
        return processUserInfoForPage(resultPage); // 处理分页结果
    }

    @Override
    public boolean updateFeedbackStatusAndReply(Long feedbackId, FeedbackStatusEnum newStatus, String reply) {
        Feedback feedback = Optional.ofNullable(baseMapper.selectById(feedbackId))
                .orElseThrow(() -> new BusinessException(HttpStatusEnum.NOT_FOUND.getCode(), "反馈不存在。"));

        // 校验状态是否合法 (如果需要，例如不允许从已解决到待处理)
        // if (newStatus == FeedbackStatusEnum.PENDING && feedback.getStatus() == FeedbackStatusEnum.RESOLVED) {
        //    throw new BusinessException(HttpStatusEnum.BAD_REQUEST, "无法将已解决的反馈重置为待处理。");
        // }

        feedback.setStatus(newStatus);
        feedback.setReply(reply);
        feedback.setReplyTime(LocalDateTime.now());

        boolean success = baseMapper.updateById(feedback) > 0;
        if (!success) {
            throw new BusinessException(HttpStatusEnum.ERROR.getCode(), "更新反馈状态和回复失败。");
        }
        return true;
    }
}